package org.tio.sitexxx.im.server.handler;

import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.sitexxx.im.common.Command;
import org.tio.sitexxx.im.common.CommandHandler;
import org.tio.sitexxx.im.common.ImPacket;
import org.tio.sitexxx.im.common.ImSessionContext;
import org.tio.sitexxx.im.common.bs.GroupChatNtf;
import org.tio.sitexxx.im.common.bs.GroupChatReq;
import org.tio.sitexxx.im.server.Ims;
import org.tio.sitexxx.im.server.utils.ImUtils;
import org.tio.sitexxx.service.model.main.ChatRecord;
import org.tio.sitexxx.service.model.main.User;
import org.tio.sitexxx.service.service.base.SensitiveWordsService;
import org.tio.sitexxx.service.service.base.UserRoleService;
import org.tio.sitexxx.service.service.base.UserService;
import org.tio.sitexxx.service.service.conf.ConfService;
import org.tio.sitexxx.service.service.conf.IpWhiteListService;
import org.tio.sitexxx.service.service.stat.ChatRecordService;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.service.vo.SimpleUser;
import org.tio.utils.SystemTimer;
import org.tio.utils.json.Json;

import cn.hutool.core.util.EscapeUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 群聊处理者
 * @author tanyaowu 
 * 2016年9月13日 上午10:16:19
 */
@CommandHandler(Command.GROUP_CHAT_REQ)
public class GroupChatReqHandler implements ImServerHandler {
	@SuppressWarnings("unused")
	private static Logger log = LoggerFactory.getLogger(GroupChatReqHandler.class);

	public static final GroupChatReqHandler me = new GroupChatReqHandler();

	public GroupChatReqHandler() {
	}

	@SuppressWarnings("unused")
	private static UserService userService = UserService.ME;

	@Override
	public void handler(ImPacket packet, ChannelContext channelContext, boolean isWebsocket) throws Exception {
		User currUser = ImUtils.getUser(channelContext);
		boolean isSupper = false;
		if (currUser != null && (UserService.isSupper(currUser))) {
			isSupper = true;// null;
		}

		SimpleUser fromUser = ImUtils.getSimpleUser(channelContext);
		if (fromUser == null) {
			ImUtils.pleaseLogin(channelContext, "登录才能聊天哦");
			return;
		}
		//没有权限
		boolean flag = UserRoleService.checkUserStatus(fromUser.getI());
		if (!flag) {
			return;
		}
		GroupChatReq groupChatReq = Json.toBean(packet.getBodyStr(), GroupChatReq.class);
		String c = StrUtil.trim(groupChatReq.getC()); //聊天内容
		if (StrUtil.isBlank(c)) {
			// 聊天内容是空
			return;
		}

		String groupid = groupChatReq.getG(); //
		String filterContent = c;
		if (!isSupper) {
			if (c.length() > 256) {
				// 聊天内容太长
				ImUtils.info(channelContext, "你发的内容有点长哦，t-io虽好，但也双拳难敌单身多年的双手^_^", null);
				return;
			}

			String ip = channelContext.getClientNode().getIp();

			if (!IpWhiteListService.isWhiteIp(ip)) {
				ImSessionContext imSessionContext = ImUtils.getImSessionContext(channelContext);
				long lastGroupChatTime = imSessionContext.getLastGroupChatTime();
				int interval = ConfService.getInt("im.group.chat.time.interval", 2000);
				long currtime = SystemTimer.currTime;
				if ((currtime - lastGroupChatTime) <= interval) {
					//发言过快
					ImUtils.info(channelContext, "发言这么快，是梁静茹给你的勇气吗", null);
					return;
				}

				imSessionContext.setLastGroupChatTime(currtime);
			}

			filterContent = SensitiveWordsService.findAndReplace(filterContent);
			filterContent = EscapeUtil.escapeHtml4(filterContent);
		}

		byte contentType = ChatRecord.ContentType.TEXT;
		groupChatAndLog(channelContext, c, filterContent, fromUser, groupid, contentType);
	}

	/**
	 * 发送群聊，并且保存日志
	 * @param channelContext
	 * @param initContent
	 * @param displayContent
	 * @param fromUser
	 * @param groupid
	 * @param contenttype
	 */
	public static void groupChatAndLog(ChannelContext channelContext, String initContent, String displayContent, SimpleUser fromUser, String groupid, Byte contenttype) {
		String sessionid = ImUtils.getToken(channelContext);
		String fromIp = channelContext.getClientNode().getIp();
		String channelContextId = channelContext.getId();

		groupChatAndLog(sessionid, initContent, displayContent, fromUser, fromIp, groupid, channelContextId, contenttype);
	}

	/**
	 * 发送群聊，并且保存日志
	 * @param sessionid
	 * @param initContent
	 * @param displayContent
	 * @param fromUser
	 * @param fromIp
	 * @param groupid
	 * @param channelContextId
	 * @param contenttype
	 */
	public static void groupChatAndLog(String sessionid, String initContent, String displayContent, SimpleUser fromUser, String fromIp, String groupid, String channelContextId,
	        Byte contenttype) {
		ChatRecord chatRecord = ChatRecordService.me.saveChatRecord(sessionid, initContent, displayContent, fromUser, fromIp, groupid, contenttype);

		GroupChatNtf groupChatNtf = new GroupChatNtf();
		groupChatNtf.setC(displayContent);
		groupChatNtf.setF(fromUser);
		groupChatNtf.setCid(channelContextId);
		groupChatNtf.setG(groupid);
		groupChatNtf.setCt(contenttype);
		groupChatNtf.setMid(String.valueOf(chatRecord.getId()));

		ImPacket imPacket = new ImPacket(Command.GROUP_CHAT_NTY, "[" + Json.toJson(groupChatNtf) + "]");
		if (Objects.equals(Const.GroupId.ALL, groupid)) {
			Ims.sendToAll(imPacket);
		} else {
			Ims.sendToGroup(groupid, imPacket);
		}
	}

	//	private ImPacket create

}
